<?php

namespace app\modules\backend\controllers;

use app\models\Base;
use app\models\Auth;
use app\models\AuthItemChild;
use app\models\AuthAssignment;
use app\tools\Re;
use Yii;

class RoleController extends BaseController
{
    public function actionRoleList()
    {
        $name = Yii::$app->request->get('name', '');
        $page = Yii::$app->request->get('page', 0);
        $query = Auth::find()->where(['type' => 1]);
        if($name){
            $query->andWhere(['like','name',$name]);
        }
        $auth = $query->limit(Auth::PAGE_SIZE)->offset($page*Auth::PAGE_SIZE)->all();
        $fields = ['name', 'description', 'created_at'];
        return Re::data([
            'data' => Base::buildParamsList($auth, $fields),
            'totalPage' => $query->count(),
            'currentPage' => $page,
            'perPage' => Auth::PAGE_SIZE
        ]);
    }

    public function actionCreateRole()
    {
        $post = Yii::$app->request->post();
        if (empty($post['name']) || empty($post['description']) || empty($post['auth_selecte'])) {
            return Re::data(null, '缺少参数', Re::ERROR);
        }
        $auth = Auth::find()->where(['name' =>$post['name'], 'type' => 1])->one();
        if ($auth) {
            return Re::data(null, '角色已存在', Re::ERROR);
        }
        $tran = Yii::$app->db->beginTransaction();
        try{
            $auth = new Auth();
            $auth->name = $post['name'];
            $auth->description = $post['description'];
            $auth->type = 1;
            $auth->created_at = time();
            $auth->updated_at = time();
            $auth->save();
            $permission_arr = $post['auth_selecte'];
            if (count($permission_arr)) {
                for ($i=0; $i < count($permission_arr); $i++) {
                    $authItemChild = new AuthItemChild();
                    $authItemChild->parent = $post['name'];
                    $authItemChild->child = $permission_arr[$i];
                    $authItemChild->save();
                }
            }
            $tran->commit();
            return Re::data();
        }catch (\Throwable $e){
            $tran->rollBack();
            throw $e;
        }
    }

    public function actionUpdateRole()
    {
        $post = Yii::$app->request->post();
        $auth = Auth::find()->where(['name' =>$post['name'], 'type' => 1])->one();
        if ($auth) {
            if($post['name'] == '超级管理员') {
                return Re::data(null, '超级管理员拥有全部权限，不可配置', Re::ERROR);
            } else {
                $name = $post['name'];
                $authAssignments = AuthAssignment::find()->where(['item_name' => $name])->all();
                //var_dump($authAssignments);die;
                $sql = "delete from auth_item where name = '$name'";
                Yii::$app->db->createCommand($sql)->execute();

                AuthAssignment::deleteAll(['item_name' => $post['name']]);
                AuthItemChild::deleteAll(['parent' => $post['name']]);

                $tran = Yii::$app->db->beginTransaction();
                try{
                    $auth_info = new Auth();
                    $auth_info->name = $post['name'];
                    $auth_info->description = $post['description'];
                    $auth_info->type = 1;
                    $auth_info->created_at = time();
                    $auth_info->updated_at = time();
                    $auth_info->save();
                    $permission_arr = $post['auth_selecte'];
                    if (count($permission_arr)) {
                        for ($i=0; $i < count($permission_arr); $i++) {
                            $authItemChild = new AuthItemChild();
                            $authItemChild->parent = $post['name'];
                            $authItemChild->child = $permission_arr[$i];
                            $authItemChild->save();
                        }
                    }

                    foreach ($authAssignments as $authAssignment) {
                        $newAuthAssignment = new AuthAssignment();
                        $newAuthAssignment->item_name = $post['name'];
                        $newAuthAssignment->created_at = $authAssignment->created_at;
                        if (!$newAuthAssignment->save()) {
                            var_dump($newAuthAssignment->getErrors());die;
                        }
                    }
                    $tran->commit();
                    return Re::data();
                }catch (\Throwable $e){
                    $tran->rollBack();
                    throw $e;
                }
            }
        } else {
            return Re::data(null, '角色不存在', Re::ERROR);
        }
    }

    public function actionRoleInfo()
    {
        $name = Yii::$app->request->post('name');
        $role = Auth::find()->where(['name' =>$name, 'type' => 1])->one();
        if ($role) {
            $data = [];
            $auth_data = [];
            $auths = AuthItemChild::find()->where(['parent' => $name])->all();
            if ($auths) {
                foreach ($auths as $auth) {
                    array_push($auth_data,$auth->child);
                }
            }
            $data = [
                'name' => $name,
                'description' => $role->description,
                'auth_data' => $auth_data
            ];
            return Re::data(['data' => $data]);
        }
        return Re::data(null, '角色不存在', Re::ERROR);
    }

    public function actionDeleteRole()
    {
        $name = Yii::$app->request->post('name');
        $role = Auth::find()->where(['name' =>$name, 'type' => 1])->one();
        if ($role) {
            $role->delete();
            AuthAssignment::deleteAll(['item_name' => $name]);
            AuthItemChild::deleteAll(['parent' => $name]);
            return Re::data();
        }
        return Re::data(null, '角色不存在', Re::ERROR);
    }
}
